package com.example.diskmonitor.service;

import com.example.diskmonitor.entity.SysFile;
import com.example.diskmonitor.repository.SysFileRepository;
import oshi.SystemInfo;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.example.diskmonitor.util.Arith;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class DiskMonitorDemo {

    @Autowired
    private SysFileRepository sysFileRepository;

    @Scheduled(fixedRateString =
            "${disk.monitor.schedule.rate}")
    public void printDiskInfo() {
        SystemInfo systemInfo = new SystemInfo();
        oshi.software.os.OperatingSystem os = systemInfo.getOperatingSystem();
        FileSystem fileSystemInfo = os.getFileSystem();
        List<OSFileStore> fileStores = fileSystemInfo.getFileStores();

        List<SysFile> newSysFiles = new ArrayList<>();

        for (OSFileStore fs : fileStores) {
            SysFile sysFile = new SysFile();
            sysFile.setDeviceName(fs.getMount());
            sysFile.setFileSystem(fs.getType());
            sysFile.setTotalSpace(formatSize(fs.getTotalSpace()));
            // 修复：使用可用空间而非总空间
            sysFile.setFreeSpace(formatSize(fs.getFreeSpace()));
            sysFile.setDiskUsage(calculateUsage(fs.getTotalSpace(), fs.getFreeSpace()));
            Optional<SysFile> existingFile = sysFileRepository.findFirstByDeviceNameAndFileSystem(
                    sysFile.getDeviceName(), sysFile.getFileSystem());
            if (!existingFile.isPresent()) {
                newSysFiles.add(sysFile);
            }

            System.out.println("设备名称: " + fs.getMount());
            System.out.println("文件系统: " + fs.getType());
            System.out.println("总容量: " + formatSize(fs.getTotalSpace()));
            System.out.println("可用空间: " + formatSize(fs.getFreeSpace()));
            System.out.println("使用率: " + sysFile.getDiskUsage() + "%");
            System.out.println("----------------------------------------");
        }

        sysFileRepository.saveAll(newSysFiles);
    }

    private String formatSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = {"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return String.format("%.2f %s", size / Math.pow(1024, digitGroups), units[digitGroups]);
    }

    public Page<SysFile> getAllDiskInfo(Pageable pageable) {   // 修改方法签名，接收Pageable参数并返回Page<SysFile>
        return sysFileRepository.findAll(pageable);    // 调用JpaRepository的分页查询方法
    }

    private String calculateUsage(long total, long free) {
        if (total == 0) return "0%";
        double usage = Arith.round(100 - (free * 100.0 / total), 2);
        return usage + "%";
    }
}
